package com.whmall.service.crm.module.companyuser.impl;

import com.whmall.component.util.DatabaseDefaultValueUtils;
import com.whmall.component.util.FieldUtils;
import com.whmall.service.crm.entity.dto.companyuser.CompanyUserDetailsRspDTO;
import com.whmall.service.crm.entity.dto.companyuser.CompanyUserKeyFieldRspDTO;
import com.whmall.service.crm.entity.dto.companyuser.CompanyUserListItemRspDTO;
import com.whmall.service.crm.module.companyuser.CompanyUserRepository;
import com.whmall.service.crm.module.companyuser.dao.CompanyUserInformationMapper;
import com.whmall.service.crm.module.companyuser.dao.CompanyUserMapper;
import com.whmall.service.crm.module.companyuser.entity.CompanyUserDO;
import com.whmall.service.crm.module.companyuser.entity.CompanyUserInformationDO;
import com.whmall.service.crm.module.companyuser.entity.qo.CompanyUserQO;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import java.util.*;
import java.util.stream.Collectors;

/**
 * CompanyUserRepositoryImpl
 *
 * @author alex
 * @since 2020/8/3
 */
@Repository
public class CompanyUserRepositoryImpl implements CompanyUserRepository {
    private final CompanyUserMapper companyUserMapper;
    private final CompanyUserInformationMapper companyUserInformationMapper;

    public CompanyUserRepositoryImpl(CompanyUserMapper companyUserMapper,
                                     CompanyUserInformationMapper companyUserInformationMapper) {
        this.companyUserMapper = companyUserMapper;
        this.companyUserInformationMapper = companyUserInformationMapper;
    }

    @Override
    public List<CompanyUserListItemRspDTO> listUserByCompany(Long companyId) {
        List<CompanyUserDO> companyUsers = companyUserMapper.listByCompanyId(companyId);
        if (companyUsers.isEmpty()) {
            return Collections.emptyList();
        }

        List<Long> companyUserIds = companyUsers.stream()
                .map(CompanyUserDO::getId)
                .collect(Collectors.toList());

        Map<Long, CompanyUserInformationDO> infoMap = companyUserInformationMapper.listByIds(companyUserIds)
                .stream()
                .collect(Collectors.toMap(CompanyUserInformationDO::getId, e -> e));

        return companyUsers.stream()
                .map(e -> {
                    CompanyUserListItemRspDTO dto = new CompanyUserListItemRspDTO();
                    dto.setId(e.getId());
                    dto.setCompanyId(e.getCompanyId());
                    dto.setName(e.getName());
                    dto.setMobile(DatabaseDefaultValueUtils.erasureMillisecondDefaultValueIfExist(e.getMobile()));
                    dto.setEmail(DatabaseDefaultValueUtils.erasureMillisecondDefaultValueIfExist(e.getEmail()));
                    dto.setQq(e.getQq());
                    dto.setIsCustomer(e.getIsCustomer());
                    dto.setIsSupplier(e.getIsSupplier());
                    dto.setIsLockedBuy(e.getIsLockedBuy());
                    dto.setIsLockedSale(e.getIsLockedSale());
                    dto.setIsDefaultUser(Objects.equals(e.getDefaultUser(), 1));
                    dto.setVerified(e.getVerified());
                    dto.setCreateTime(e.getCreateTime());
                    Optional.ofNullable(infoMap.get(e.getId()))
                            .ifPresent(info -> {
                                dto.setCustomerLockReason(info.getCustomerLockReason());
                                dto.setSupplierLockReason(info.getSupplierLockReason());
                                dto.setPurchaserComment(info.getPurchaserComment());
                                dto.setSupplierContact(info.getSupplierContact());
                                dto.setInvoiceEmail(info.getInvoiceEmail());
                            });
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<CompanyUserKeyFieldRspDTO> getAvailableCompanyUsers(Long companyId) {
        Assert.isTrue(companyId != null, "参数错误");
        List<CompanyUserDO> companyUsers = companyUserMapper.listBy(
                CompanyUserQO.builder().companyId(companyId).isLogout(false)
                        .orderBy("default_user").build());
        return companyUsers.stream()
                .map(e ->
                        CompanyUserKeyFieldRspDTO.builder()
                                .id(e.getId())
                                .name(e.getName())
                                .email(FieldUtils.unwrapString(e.getEmail()))
                                .mobile(FieldUtils.unwrapString(e.getMobile()))
                                .qq(e.getQq())
                                .companyId(e.getCompanyId())
                                .defaultUser(FieldUtils.unwrapDefault(e.getDefaultUser()))
                                .build()
                ).collect(Collectors.toList());
    }

    @Override
    public CompanyUserDetailsRspDTO getDetailsById(Long companyId, Long companyUserId) {
        return Optional.ofNullable(companyUserMapper.getById(companyUserId))
                .filter(e -> e.getCompanyId().equals(companyId))
                .map(e -> {
                    CompanyUserDetailsRspDTO dto = new CompanyUserDetailsRspDTO();
                    dto.setId(e.getId());
                    dto.setCompanyId(e.getCompanyId());
                    dto.setName(e.getName());
                    dto.setMobile(DatabaseDefaultValueUtils.erasureMillisecondDefaultValueIfExist(e.getMobile()));
                    dto.setEmail(DatabaseDefaultValueUtils.erasureMillisecondDefaultValueIfExist(e.getEmail()));
                    dto.setIsCustomer(e.getIsCustomer());
                    dto.setIsSupplier(e.getIsSupplier());
                    dto.setTel(e.getTel());
                    dto.setQq(e.getQq());
                    dto.setFax(e.getFax());
                    dto.setGender(e.getGender());
                    dto.setBirthday(e.getBirthday());
                    dto.setIsVerifiedEmail(e.getIsVerifiedEmail());
                    dto.setBdSource(e.getBdSource());
                    dto.setExpressCompany(e.getExpressCompany());

                    Optional.ofNullable(companyUserInformationMapper.getById(companyUserId))
                            .ifPresent(info -> {
                                dto.setPosition(info.getPosition());
                                dto.setDepartment(info.getDepartment());
                                dto.setPurchaserComment(info.getPurchaserComment());
                                dto.setSupplierContact(info.getSupplierContact());
                                dto.setAvatar(info.getAvatar());
                                dto.setIsAutoQuotation(info.getIsAutoQuotation());
                                dto.setNotifyBitmap(info.getNotifyBitmap());
                                dto.setPreference(info.getPreference());
                                dto.setInvoiceEmail(info.getInvoiceEmail());
                            });
                    return dto;
                })
                .orElse(null);
    }

    @Override
    public List<CompanyUserDO> listForDefaultUsersByCompanyIdIn(List<Long> companyIds) {
        if (companyIds.isEmpty()) {
            return Collections.emptyList();
        }

        return companyUserMapper.listByCompanyIdsAndDefaultIsTrue(companyIds
                .stream()
                .distinct()
                .collect(Collectors.toList()));
    }
}
